{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 计算沪深300股指期货和中证500股指期货基差"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 本段代码为量化小学课后作业, 利用quantOS系统计算股指期货与股票指数和股票ETF的基差\n",
    "## 提示：请在提示处补全代码完成作业"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 系统设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import datetime\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_style('darkgrid')\n",
    "sns.set_context('poster')\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from jaqs.data import RemoteDataService\n",
    "import jaqs.util as jutil"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 登录信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 如果没有使用quantos金融终端，请自行替换phone,token内容\n",
    "dataview_dir_path = '.'\n",
    "backtest_result_dir_path = '.'\n",
    "\n",
    "import os\n",
    "phone = os.environ.get('QUANTOS_USER')\n",
    "token = os.environ.get('QUANTOS_TOKEN')\n",
    "\n",
    "data_config = {\n",
    "  \"remote.data.address\": \"tcp://data.quantos.org:8910\",\n",
    "  \"remote.data.username\": phone,\n",
    "  \"timeout\": 3600,\n",
    "  \"remote.data.password\": token\n",
    "}\n",
    "\n",
    "ds = RemoteDataService()\n",
    "ds.init_from_config(data_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## IF 基差分析--观察2014年12月IF期货大幅升水沪深300指数的情况"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第一步：数据下载"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 设定起始日期及指数列表\n",
    "start_date = 20140901\n",
    "end_date   = 20150119\n",
    "index_list_IF = ['IF1412.CFE', 'IF1501.CFE', '000300.SH', '510300.SH']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "df_all_IF = pd.DataFrame()\n",
    "for single_index in index_list_IF:\n",
    "    df, msg = ds.daily(single_index, start_date, end_date, fields = 'close')\n",
    "    df['trade_date'] = df['trade_date'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d').date())\n",
    "    df = df.set_index('trade_date')\n",
    "    df = df[['close']]\n",
    "    df.columns = [single_index]\n",
    "    df_all_IF = pd.concat([df_all_IF, df], axis = 1)\n",
    "df_all_IF.head(20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第二步：计算期现差及升贴水比例\n",
    "### 注意：basis_index, basis_index_pct, basis_ETF和basis_ETF_pct的计算过程请根据课程内容补充完整"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# IF1412.CFE\n",
    "basis_if1412 = pd.DataFrame()\n",
    "\n",
    "# 计算股指期货相对于指数的基差\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_if1412['basis_index']     = \n",
    "basis_if1412['basis_index_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "# 计算股指期货相对于ETF的基差 (小提示：利用ETF和股指期货进行期现套利需保证两者的名义金额大致相等，即需将ETF价格乘以调整因子adj_factor\n",
    "# 再与股指期货进行比较，计算基差)\n",
    "adj_factor = 1000\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_if1412['basis_ETF']     = \n",
    "basis_if1412['basis_ETF_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "basis_if1412 = basis_if1412.dropna()\n",
    "\n",
    "# IF1501.CFE\n",
    "basis_if1501 = pd.DataFrame()\n",
    "\n",
    "# 计算股指期货相对于指数的基差\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_if1501['basis_index']     = \n",
    "basis_if1501['basis_index_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "# 计算股指期货相对于ETF的基差 (小提示：利用ETF和股指期货进行期现套利需保证两者的名义金额大致相等，即需将ETF价格乘以调整因子adj_factor\n",
    "# 再与股指期货进行比较，计算基差)\n",
    "adj_factor = 1000\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_if1501['basis_ETF']     = \n",
    "basis_if1501['basis_ETF_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "basis_if1501 = basis_if1501.dropna()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第三步：画图展示期限差及升贴水比例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IF1412期限差点数\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_if1412.index, basis_if1412.basis_index, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_if1412.index, basis_if1412.basis_ETF, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis between IF1412.CFE and 000300.SH/510300.SH', fontsize=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IF1412升贴水比例\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_if1412.index, basis_if1412.basis_index_pct, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_if1412.index, basis_if1412.basis_ETF_pct, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis(in percent) between IF1412.CFE and 000300.SH/510300.SH', fontsize=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IF1501期限差点数\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_if1501.index, basis_if1501.basis_index, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_if1501.index, basis_if1501.basis_ETF, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis between IF1501.CFE and 000300.SH/510300.SH', fontsize=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IF1501升贴水比例\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_if1501.index, basis_if1501.basis_index_pct, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_if1501.index, basis_if1501.basis_ETF_pct, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis(in percent) between IF1501.CFE and 000300.SH/510300.SH', fontsize=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## IC 基差分析--观察2016年上半年IC期货大幅贴水中证500指数的情况"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第一步：数据下载"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 设定起始日期及指数列表\n",
    "start_date = 20151019\n",
    "end_date   = 20160630\n",
    "index_list_IC = ['IC1606.CFE', '000905.SH', '510500.SH']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "df_all_IC = pd.DataFrame()\n",
    "for single_index in index_list_IC:\n",
    "    df, msg = ds.daily(single_index, start_date, end_date, fields = 'close')\n",
    "    df['trade_date'] = df['trade_date'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d').date())\n",
    "    df = df.set_index('trade_date')\n",
    "    df = df[['close']]\n",
    "    df.columns = [single_index]\n",
    "    df_all_IC = pd.concat([df_all_IC, df], axis = 1)\n",
    "df_all_IC.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第二步：计算期现差及升贴水比例\n",
    "### 注意：basis_index, basis_index_pct, basis_ETF和basis_ETF_pct的计算过程请根据课程内容补充完整"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# IC1606.CFE\n",
    "basis_ic1606 = pd.DataFrame()\n",
    "\n",
    "# 计算股指期货相对于指数的基差\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_ic1606['basis_index']     = \n",
    "basis_ic1606['basis_index_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "# 计算股指期货相对于ETF的基差 (小提示：利用ETF和股指期货进行期现套利需保证两者的名义金额大致相等，即需将ETF价格乘以调整因子adj_factor\n",
    "# 再与股指期货进行比较，计算基差)\n",
    "adj_factor = 1000\n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "basis_ic1606['basis_ETF']     = \n",
    "basis_ic1606['basis_ETF_pct'] = \n",
    "# ----------------------------------------------------------------------------------------------------------------\n",
    "\n",
    "basis_ic1606 = basis_ic1606.dropna()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第三步：画图展示期限差及升贴水比例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IC1606期限差点数\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_ic1606.index, basis_ic1606.basis_index, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_ic1606.index, basis_ic1606.basis_ETF, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis between IC1606.CFE and 000905.SH/510500.SH', fontsize=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 展示IC1606升贴水比例\n",
    "fig, ax1 = plt.subplots(figsize=(18, 9))\n",
    "ax1.plot(basis_ic1606.index, basis_ic1606.basis_index_pct, label = 'basis with index', color = 'blue', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.plot(basis_ic1606.index, basis_ic1606.basis_ETF_pct, label = 'basis with ETF', color = 'green', linewidth = 0.8, alpha = 0.8)\n",
    "ax1.axhline(y = 0, color = 'red', linestyle = '--', linewidth = 0.8, alpha = 0.8)\n",
    "plt.legend(fontsize = 15)\n",
    "plt.title('Daily basis (in percent) between IC1606.CFE and 000905.SH/510500.SH', fontsize=15)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
